package com.kintreda.ieco_server.module.organization.web;

import com.kintreda.ieco_server.bean.account.Organization;
import com.kintreda.ieco_server.bean.account.Role;
import com.kintreda.ieco_server.bean.account.User;
import com.kintreda.ieco_server.bean.goods.Places;
import com.kintreda.ieco_server.bean.massage.Massage;
import com.kintreda.ieco_server.bean.org.OrgSetting;
import com.kintreda.ieco_server.bean.place.Place;
import com.kintreda.ieco_server.core.repository.IBaseRepository;
import com.kintreda.ieco_server.core.web.BaseController;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.account.service.IRoleService;
import com.kintreda.ieco_server.module.account.service.IUserService;
import com.kintreda.ieco_server.module.api.service.IMassageService;
import com.kintreda.ieco_server.module.order.service.IPlacesService;
import com.kintreda.ieco_server.module.order.service.IUsageRecordService;
import com.kintreda.ieco_server.module.organization.service.IOrgSettingService;
import com.kintreda.ieco_server.module.organization.service.IOrganizationService;
import com.kintreda.ieco_server.module.place.service.IPlaceService;
import com.kintreda.ieco_server.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 组织机构Controller
 *
 * @Created by IntelliJ IDEA
 * @Project_Name ieco_server
 * @Package com.kintreda.ieco_server.module.organization.web
 * @Author ZhongYao_H
 * @Date 2019/4/28:17:36
 * @Year 2019 Month 04 Day 28
 * @Date_zh 2019 年 四月 星期日
 */
@Controller
@RequestMapping("/organ")
public class OrganController extends BaseController {

    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IBaseRepository<Organization,String> orgRepository;
    @Autowired
    IMassageService massageService;
    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IPlaceService placeService;
    @Autowired
    IPlacesService placesService;
    @Autowired
    IOrgSettingService orgSettingService;
    @Autowired
    IUsageRecordService usageRecordService;

    @RequestMapping("/orgset")
    public ModelAndView orgsetting(String id){
        return new ModelAndView("account/org/org-setting").addObject("id",id);
    }

    @RequestMapping(value = "/orgset",method = RequestMethod.POST)
    @ResponseBody
    public Object orgsetting(OrgSetting orgSetting){
        OrgSetting org = orgSettingService.getByOrgId(orgSetting.getOrgId());
        Organization organization = organizationService.get(orgSetting.getOrgId());
        organization.setUpdateDate(DateUtil.getDate(DateUtil.YYYY_MM_DD_HH_MM_SS));
        if (org==null){
            return R.error("设置错误请联系管理员!");
        }
        org.setFrequency(orgSetting.getFrequency());
        org.setWorkingTime(orgSetting.getWorkingTime());
        org.setRecently(orgSetting.getDate()+" "+orgSetting.getRecently());
        orgSettingService.update(org);
        organizationService.update(organization);
        return R.ok("操作成功!");
    }

    /**
     *
     * 模糊查询机构
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ResponseBody
    public Object query(String name,String tel)  {
        List<String> params = new ArrayList<>();
        StringBuffer hql = new StringBuffer("from Organization ");
        boolean flag = true;
        if (StringUtils.isNotBlank(name)){
            if (flag){
                hql.append(" where ");
            }else {
                hql.append(" and ");
            }
            hql.append(" name like ? ");
            params.add(name);
            flag = false;

        }

        if (StringUtils.isNotBlank(tel)){
            if (flag){
                hql.append(" where ");
            }else {
                hql.append(" and ");
            }
            hql.append(" administratorTel like ? ");
            params.add(tel);

        }

        return organizationService.query(hql.toString(),params.toArray());

    }


    @RequestMapping(value = "/allocation",method = RequestMethod.GET)
    public ModelAndView allocation(String id){
        ModelAndView andView = new ModelAndView("account/org/org-set-sack");
        String orgId = organizationService.get(id).getOrgid();
        List<Organization> query = organizationService.query("from Organization where orgid = ? ", new Object[]{orgId});
        for (Organization organization : query) {
            Places places = null;
            places = placesService.getByOrgId(organization.getAdminId(), "1");
            if (places==null){
                organization.setNum("0");
            }else {
                String orgAdminId = null;
                try {
                    orgAdminId = organization.getAdminId();
                }catch (Exception e){}
                if (orgAdminId!=null){
                    Long uses = usageRecordService.countUse(orgAdminId);
                    long totalNum = Long.parseLong(places.getNum()) ;
                    Long remaining = totalNum - uses;
                    organization.setNum(remaining.toString());
                }

            }
        }

        Places places = null;
        places = placesService.getByOrgId(getUser().getId(), "1");
        if (places==null){

            places = new Places();
        }

        andView.addObject("places",places);
        andView.addObject("orgs",query);
        andView.addObject("id",id);
        return andView;
    }

    @RequestMapping(value = "/allocation",method = RequestMethod.POST)
    @ResponseBody
    public Object allocation(String id,String mobile,String sendId,String num,String type){

        //将要分配袋子的子机构
        Organization organization = organizationService.get(id);
        if (organization.getAdminId().equals("")){
            return R.error("此机构还未设置管理员! 请先设置管理员");
        }

        if(num .equals("") || num == null || Integer.parseInt(num)<=0){
            return R.error("分配的数量不能小于等于0");
        }

        Places pla = placesService.getByOrgId(organization.getAdminId(),"1");

        if(type.equals("0")){
            // 选择从总机构可分配袋子 分配
            String userId = getUser().getId();

            //总机构可分配袋子
            Places places = placesService.getByOrgId(userId, "1");
            if (places==null ){
                return R.error("机构无可分配袋子");
            }
            //总机构可分配袋子数量
            Integer orgSackNum =  Integer.parseInt(places.getNum());
            if (orgSackNum==0){
                return R.error("机构无可分配袋子");
            }
            //分配的袋子数量
            Integer allNum = Integer.parseInt(num);

            if (allNum>orgSackNum){
                return R.error("分配的数量大于可分配数量,请选择可分配的数量!");
            }

            if (pla==null){
                pla = new Places();
                pla.setOrgId(organization.getAdminId());
                pla.setType("1");
                placesService.save(pla);

            }

            //将要分配袋子的子机构剩余袋子数量
            Integer childNum = Integer.parseInt(pla.getNum());

            //总机构剩余
            Integer surplus = orgSackNum-allNum;
            //子机构剩余
            childNum = allNum + childNum;
            places.setNum(surplus+"");
            pla.setNum(childNum+"");

            placesService.update(pla);
            placesService.update(places);
            return R.ok("分配成功!");


        }else {
            //选择从子机构分配

            //子机构可分配袋子
            Places places = placesService.getByOrgId(organizationService.get(sendId).getAdminId(),"1");
            if (places==null){
                return R.error("子机构无可分配袋子");
            }
            if (places.getNum().equals("0")){
                return R.error("子机构无可分配袋子");
            }

            //分配袋子
            Integer allNum = Integer.parseInt(num);

            //子机构袋子(发)
            Integer childNum = Integer.parseInt(places.getNum());
            if (allNum>childNum){
                return R.error("分配的数量大于可分配数量,请选择可分配的数量!");
            }

            if (pla==null){
                pla = new Places();
                pla.setOrgId(organization.getAdminId());
                pla.setType("1");
                placesService.save(pla);

            }

            //将要分配袋子的子机构剩余袋子数量(收)
            Integer thisOrg = Integer.parseInt(pla.getNum());
            thisOrg = thisOrg+allNum;
            childNum = childNum-allNum;
            places.setNum(childNum+"");
            pla.setNum(thisOrg+"");

            placesService.update(pla);
            placesService.update(places);
            return R.ok("分配成功");
        }
    }



    @RequestMapping(value = "/setadmin",method = RequestMethod.GET)
    public ModelAndView setadmin(String id){
        ModelAndView andView = new ModelAndView("account/org/edit-admin");
        User user = null;
        try{
            String adminId = organizationService.get(id).getAdminId();
            user = userService.get(adminId);
        }catch (Exception e){}
        andView.addObject("id",id);
        andView.addObject("user",user);
        return andView;
    }

    @RequestMapping(value = "/setadmin",method = RequestMethod.POST)
    @ResponseBody
    public Object setadmin(String id,String moblie){
        Organization organization = organizationService.get(id);
        String oldAdmin = organization.getAdminId();
        String adminID="";
        try {
             adminID = organization.getAdminId();
        }catch (Exception e){
        }

        User user = userService.queryByMobile(moblie);
        if (user == null){
            return R.error("改手机号未注册,请先注册再设置为管理员");
        }
        Organization byAndminId = organizationService.getByAndminId(user.getId());
        if (byAndminId!=null){
            return R.error("该手机号已绑定为其它机构/部门管理员!");
        }

        if (!adminID.equals("")){
            Places places = placesService.getByOrgId(adminID, "1");
            if (places!=null){
                places.setOrgId(user.getId());
                placesService.update(places);
            }
        }

        organization.setAdminId(user.getId());
        user.setType("4");
        user.setOrgId(organization.getOrgid());
        userService.update(user);
        organizationService.update(organization);
        if (!oldAdmin.equals("")){
            User oldUser = userService.get(oldAdmin);
            oldUser.setType("2");
            oldUser.setOrgId("");
            oldUser.setPid("");
            userService.update(oldUser);
            sendMsg("[消息]管理员变更,您已不是"+organization.getName()+" 管理员", "于"+DateUtil.getDate(DateUtil.YYYY_MM_DD_HH_CH_CM_CS)+"您已不是 "+organization.getName()+" 管理员",oldUser.getId());
        }

        sendMsg("[消息]您已成为 "+organization.getName()+" 管理员", "于"+DateUtil.getDate(DateUtil.YYYY_MM_DD_HH_CH_CM_CS)+"您已成为 "+organization.getName()+" 管理员",user.getId());
        return R.ok("修改成功!");
    }

    @RequestMapping("/tree")
    public ModelAndView tree() {
        return new ModelAndView("account/org/organization-list");
    }

    @RequestMapping("/list")
    public ModelAndView list() {
        User user = getUser();
        if (user==null){
            return null;
        }
        if (user.getType().equals("3")){
            ModelAndView andView = new ModelAndView("account/org/organ-list");
            return andView.addObject("user",user);
        }else {
            ModelAndView andView = new ModelAndView("account/org/organ-list-admin");
            return andView.addObject("user",user);
        }

    }

    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ResponseBody
    public Object query(@RequestParam(name = "t",defaultValue = "0") String t) {

        List<Organization> organizations = null;
        if ("1".equals(getUser().getType())) {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT * FROM organization o  where o.nature = ? and orgStatus = ? ORDER  BY o.updateDate DESC");
            return orgRepository.findListBySql(sql.toString(), new Object[]{"0","2"});
        } else {
            if ("1".equals(t)){
                StringBuffer sql = new StringBuffer();
                sql.append("SELECT o.*,t.name as pname FROM organization o LEFT JOIN organization t ON  o.pid = t.id ");
                sql.append("WHERE  t.id = ? ");
                sql.append(" ORDER  BY o.createDate DESC");
               return orgRepository.findListBySql(sql.toString(), new Object[]{getUser().getOrgId()});
            }else {
            organizations = organizationService.queryByChild(getUser().getPid());
            }
        }
        return organizations;
    }


    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @ResponseBody
    public Object query() {

        List<Organization> organizations = null;
        if ("1".equals(getUser().getType())) {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT *FROM organization o LEFT JOIN organization t ON  o.pid = t.id where o.nature = ? ORDER  BY o.createDate DESC");
            return orgRepository.findListBySql(sql.toString(), new Object[]{"0"});
        } else {
                organizations = organizationService.queryByChild(getUser().getPid());
        }
        return organizations;
    }


    @RequestMapping("/add")
    public ModelAndView add() {
        ModelAndView andView =new ModelAndView("account/org/organization-add-org");
        andView.addObject("orgid",getUser().getOrgId());
        return andView;
    }

    @RequestMapping("/add/{pid}")
    public ModelAndView add(@PathVariable("pid") String pid) {

          ModelAndView andView =    new ModelAndView("account/org/organization-add").addObject("parent", organizationService.get(pid));
            andView.addObject("pid",pid);
            andView.addObject("orgid",getUser().getOrgId());
          return andView;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public R add(Organization organization) {
        try {
            if (organizationService.isExist(organization.getName())){
               return R.error("该名称已被占用");
            }

            Organization orgPid = organizationService.get(organization.getOrgid());
            organization.setIcon(orgPid.getIcon());
            organization.setAddress(orgPid.getAddress());
            organization.setLongitude(orgPid.getLongitude());
            organization.setNature("1");
            organization.setType(orgPid.getType());
            organization.setLatitude(orgPid.getLatitude());

            organizationService.save(organization);
            return R.ok("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统异常请联系管理员");
        }


    }


    @RequestMapping("/edit/{pid}")
    public ModelAndView edit(@PathVariable("pid") String pid) {
        ModelAndView andView =  new ModelAndView("account/org/organization-edit");

        Organization organization = organizationService.get(pid);
        andView.addObject("parent", organization);
        andView.addObject("id",pid);
        andView.addObject("pname",organizationService.get(organization.getPid().toString()).getName());
        return andView;
    }


    @RequestMapping("/edit")
    @ResponseBody
    public R edit(Organization organization) {
        try {
            Organization organizDB = organizationService.get(organization.getId());
            organizDB.setName(organization.getName());
            organizationService.update(organizDB);
            return R.ok("修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统异常");
        }
    }

    @RequestMapping(value = "/delete/{pid}", method = RequestMethod.POST)
    @ResponseBody
    public R delete(@PathVariable("pid") String pid) {
        int updates = organizationService.getJdbcTemplate().update("update organization set status= 1 where id = '" + pid + "' or pid = '" + pid+"'");
        return updates>0?R.ok("删除成功！"):R.error("删除失败 ，等会在试试");
    }



    //============== 机构申请

    @RequestMapping( "/applylist")
    public ModelAndView applylist(){

        return new ModelAndView("account/org/apply-list");

    }

    @RequestMapping(value = "/applylist",method = RequestMethod.POST)
    @ResponseBody
    public Object applylist(String name){
        String hql = null;
        List<Object> params = new LinkedList();
        if (StringUtils.isNotBlank(name)){
            hql = "from Organization where name like ? and orgStatus = ?";
            params.add(name);
            params.add(1);
            return organizationService.query(hql,params.toArray());
        }

        hql = "from Organization where orgStatus = ?";
        params.add(1);
        return organizationService.query(hql,params.toArray());

    }


    @RequestMapping( value = "/audit",method = RequestMethod.GET)
    public ModelAndView apply(String id){
        Organization organization = organizationService.get(id);
        organizationService.update(organization);
        ModelAndView andView = new ModelAndView("account/org/org-apply");
        andView.addObject("org",organization);
        return andView;

    }

    @RequestMapping( value = "/audit",method = RequestMethod.POST)
    @ResponseBody
    public Object apply(String id, Integer audit, final String msg){
        Organization organization = organizationService.get(id);
        organization.setOrgStatus(audit);
        organizationService.update(organization);
        String title = null;
        switch (audit){
            case 2:
                title = "机构申请通过";
                User user = userService.get(organization.getAdminId());
                user.setType("3");
                user.setPid(id);
                user.setOrgId(organization.getId());
                Set<Role> roles = new HashSet<>();
                Role role = roleService.getRoleByCode("orgman");
                if (role!=null){
                    roles.add(role);
                    user.setRoles(roles);
                }
                //审核通过后将机构在地图上标注出来
                Place place = new Place();
                place.setAddress(organization.getAddress());
                place.setLatitude(organization.getLatitude());
                place.setLongitude(organization.getLongitude());
                place.setName(organization.getName());
                place.setType("1");
                place.setOrgId(organization.getId());

                OrgSetting orgSetting = new OrgSetting();
                orgSetting.setOrgId(organization.getId());
                orgSetting.setFrequency("");
                orgSettingService.save(orgSetting);

                placeService.save(place);
                userService.update(user);
                break;

            case 3:
                title = "机构申请被驳回";
                break;
             default:
                    break;
        }
        final Massage massage = new Massage();
        massage.setTitle(title);
        massage.setDestination(organization.getAdminId());
        massage.setBody(msg);
        massage.setStatus("0");//未读
        massageService.saveOrUpdate(massage);
        return R.ok("处理成功!");

    }

    private void sendMsg(String title,String center,String userId){
        Massage massage = new Massage();
        massage.setStatus("0");
        massage.setTitle(title);
        massage.setBody(center);
        massage.setDestination(userId);
        massageService.save(massage);
    }


}
